<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="支付宝AppID" prop="appid">
        <el-input
          v-model="queryParams.appid"
          placeholder="请输入支付宝AppID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支付宝订单号" label-width="80" prop="tradeNo">
        <el-input v-model="queryParams.tradeNo" placeholder="请输入支付宝订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" label-width="80" prop="status">
        <!-- <el-input v-model="queryParams.status" placeholder="请输入订单状态: 1 未支付, 2 已支付, 3 已取消, 4 已退款, 5 已关闭" clearable
          @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.status" clearable @change="handleQuery" placeholder="请选择订单状态">
          <el-option v-for="item in orderOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['admin:admin:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['admin:admin:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['admin:admin:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['admin:admin:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="adminList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="25" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="姓名" align="center" prop="surname" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span>{{ scope.row.sex == 1 ? "男" : "女" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ scope.row.type == 1 ? "单字" : "双字" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" align="center" prop="birthday" />
      <el-table-column label="订单创建时间" align="center" prop="createTime" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="备注" align="center" prop="remarks" />

      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <!-- <el-table-column label="支付宝AppID" align="center" prop="appid" /> -->
      <!-- <el-table-column label="商品ID" align="center" prop="productId" /> -->
      <!-- <el-table-column label="商品单价" align="center" prop="productPrice" /> -->
      <!-- <el-table-column label="商品数量" align="center" prop="productNumber" /> -->
      <!-- <el-table-column label="商品总价" align="center" prop="totalPrice" /> -->
      <!-- <el-table-column label="订单标题" align="center" prop="subject" /> -->
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)" effect="dark">
            {{ statusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="支付宝订单号" align="center" prop="tradeNo" /> -->
      <!-- <el-table-column label="订单支付时间" align="center" prop="payTime" /> -->
      <!-- <el-table-column label="订单关闭时间" align="center" prop="closeTime" /> -->
      <!-- <el-table-column label="订单退款时间" align="center" prop="refundTime" /> -->
      <!-- <el-table-column label="商品原价" align="center" prop="productOriginalPrice" /> -->
      <!-- <el-table-column label="名字" align="center" prop="names" /> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['admin:admin:remove']"
          >删除</el-button>
        </template>
</el-table-column> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.orderNames !== null" size="mini" type="text" icon="el-icon-tickets"
            @click="handleLook(scope.row)">查看</el-button>
          <el-button v-if="scope.row.orderNames == null && scope.row.status == 2" size="mini" type="text"
            icon="el-icon-document-add" @click="handleGenerate(scope.row)">手动生成</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改姓名订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="姓名" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <div>
        <!-- <span></span> -->
        <!-- <span v-for="item in orderNames" :key="item">{{ item }}</span> <br> -->

        <!-- <ul>
        <li v-for="item in orderNames" :key="item">{{ surname }} {{  item}}</li>
      </ul> -->
        <table style="text-align: center;margin: 0 auto;">
          <tr v-for="(chunk, index) in chunkedOrderNames" :key="index">
            <td v-for="item in chunk" :key="item">
              {{ surname }}{{ item }}
            </td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listAdmin, getAdmin, delAdmin, addAdmin, updateAdmin, pathMethodName } from "@/api/admin/admin";

export default {
  name: "Admin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 姓名订单表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productType: 2,
        appid: null,
        status: null,
        orderNo: null,
        tradeNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      statusMapping: {
        1: { label: '未支付', type: 'warning' },
        2: { label: '已支付', type: 'success' },
        3: { label: '已取消', type: 'info' },
        4: { label: '已退款', type: 'danger' },
        5: { label: '已关闭', type: 'info' }
      },
      orders: [
        { status: 1 },
        { status: 2 },
        { status: 4 },
      ],
      dialogVisible: false,
      orderNames: [],
      orderOptions: [
        { value: 1, label: '未支付' },
        { value: 2, label: '已支付' },
        { value: 3, label: '已取消' },
        { value: 4, label: '已退款' },
        { value: 5, label: '已关闭' }
      ],
      fullscreenLoading: false
    };
  },
  created() {
    this.getList();
  },
  computed: {
    chunkedOrderNames() {
      const size = 10; // 每行显示3个
      const result = [];
      for (let i = 0; i < this.orderNames.length; i += size) {
        result.push(this.orderNames.slice(i, i + size));
      }
      return result;
    }
  },
  methods: {

    statusLabel(status) {
      const map = {
        1: '未支付',
        2: '已支付',
        3: '已取消',
        4: '已退款',
        5: '已关闭'
      };
      return map[status] || '未知';
    },
    statusTagType(status) {
      const map = {
        1: 'warning',
        2: 'success',
        3: 'info',
        4: 'danger',
        5: 'default'
      };
      return map[status] || 'default';
    },
    /** 查询姓名订单列表 */
    getList() {
      this.loading = true;
      listAdmin(this.queryParams).then(response => {
        this.adminList = response.rows;
        // response.rows.forEach(item => {
        //   if (item.orderNames && typeof item.orderNames === 'string') {
        //     item.orderNames = item.orderNames.split(',').map(name => name.trim()); // 转为数组
        //   }
        // });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        surname: null,
        sex: null,
        type: null,
        birthday: null,
        userId: null,
        appid: null,
        productId: null,
        productPrice: null,
        productNumber: null,
        totalPrice: null,
        subject: null,
        status: null,
        orderNo: null,
        createTime: null,
        payTime: null,
        closeTime: null,
        refundTime: null,
        productOriginalPrice: null,
        tradeNo: null,
        names: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加姓名订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAdmin(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改姓名订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAdmin(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAdmin(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除姓名订单编号为"' + ids + '"的数据项？').then(function () {
        return delAdmin(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/admin/export', {
        ...this.queryParams
      }, `admin_${new Date().getTime()}.xlsx`)
    },
    handleLook(row) {
      console.log(row);
      if (row.orderNames && typeof row.orderNames === 'string') {
        row.orderNames = row.orderNames.split(',').map(name => name.trim()); // 转为数组
      }
      console.log(row.orderNames);
      this.surname = row.surname
      this.orderNames = row.orderNames
      this.dialogVisible = true
    },
    handleGenerate(row) {
      console.log(row);
      let birthday = row.birthday + ":" + "00"
      console.log(birthday)
      const reqBody = {
        birthday,
        surname: row.surname,
        sex: row.sex,
        type: row.type,
        orderNo: row.orderNo
      }
      this.fullscreenLoading = true;
      pathMethodName(reqBody).then(res => {
        if (res.success = true) {
          setTimeout(() => {
            this.fullscreenLoading = false;
          }, 2000);
          this.$message({
            message: '已经生成',
            type: 'success'
          });
        }

        this.getList();
      }).catch(err => {

      })

    },
    handleClose(done) {
      done();
    },


  }
};
</script>
